from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView

from api.models import Teachers
from api.serializers import TeacherSerializer, TeacherDeSerializer


class TeachersAPIView(APIView):

    def get(self, request, *args, **kwargs):
        tea_id = kwargs.get('id')
        if tea_id:
            tea_obj = Teachers.objects.get(pk=tea_id)
            teacher_serializer = TeacherSerializer(tea_obj).data
            return Response({
                'status': 200,
                'message': '查询单个教师成功',
                'results': teacher_serializer
            })
        else:
            teacher_objects_all = Teachers.objects.all()
            tea_data = TeacherSerializer(teacher_objects_all, many=True).data
            return Response({
                'status': 200,
                'message': '查询所有教师成功',
                'results': tea_data
            })

    def post(self, request, *args, **kwargs):
        request_data = request.data
        if not isinstance(request_data, dict) or request_data == {}:
            return Response({
                'status': 400,
                'message': '参数有误',
            })
        serializer = TeacherDeSerializer(data=request_data)
        if serializer.is_valid():
            tea_ser = serializer.save()
            return Response({
                'status': 200,
                'message': '教师添加成功',
                'results': TeacherSerializer(tea_ser).data
            })
        else:
            return Response({
                'status': 400,
                'message': '教师添加失败',
                'results': serializer.errors
            })

    def delete(self, request, *args, **kwargs):
        tea_id = kwargs.get('id')
        if tea_id:
            tea_obj = Teachers.objects.get(pk=tea_id)
            try:
                tea_obj.delete()
                return Response({
                    'status': 200,
                    'message': '教师删除成功',
                })
            except:
                return Response({
                    'status': 400,
                    'message': '教师删除失败，请检查网络',
                })
